package com.learnspringcloud.order.controller;

import com.learnspringcloud.order.client.ProductClient;
import com.learnspringcloud.order.dataobject.ProductInfo;
import com.learnspringcloud.order.dto.CartDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * @author Lin
 * @date 2018/9/21 0021
 */
@RestController
@Slf4j
public class ClientController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;

    @GetMapping("test")
    public String test() {
        return "test";
    }

    @GetMapping("getProductMsg")
    public String getProductMsg() {
//        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
//        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort()) + "/msg";
//
//        RestTemplate restTemplate = new RestTemplate();
//        String response = restTemplate.getForObject(url, String.class);
//        String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);
        String response = productClient.getProductMsg();
        log.info(response);
        return response;
    }

    @GetMapping("getProductList")
    public Object getProductList() {
        List<ProductInfo> productInfoList = productClient.listForOrder(Arrays.asList("157875196366160022"));
        log.info("response, {}", productInfoList);
        return productInfoList;
    }

    @GetMapping("/productDecreaseStock")
    public String productDecreaseStock() {
        productClient.decreaseStock(Arrays.asList(new CartDTO("157875196366160022", 3)));

        return "OK";
    }
}
